package com.liyi.letter.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liyi.letter.common.result.Result;
import com.liyi.letter.system.entity.Department;
import com.liyi.letter.system.entity.Employee;
import com.liyi.letter.system.service.DepartmentService;
import com.liyi.letter.system.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: letter_parent
 * @description
 * @author: tianwen
 * @create: 2023-06-06 11:26
 **/
@RestController
@RequestMapping("/department/system")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private EmployeeService employeeService;

    /**
     * 对部门进行添加操作
     * @param department
     * @return
     */
    @PostMapping("/add")
    public Result<Department> add(@RequestBody Department department){
        boolean success = departmentService.save(department);
        if (success){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    /**
     * 根据id删除部门
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public Result<Department> delete(@PathVariable String id){
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department_id",id);
        Employee employee = new Employee();
        employee.setDepartmentId(0L);
        employeeService.update(employee, queryWrapper);
        boolean b = departmentService.removeById(id);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    /**
     * 根据名字分页查找
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page/{page}/{pageSize}")
    public Result page(@PathVariable Integer page, @PathVariable Integer pageSize,String name){
        Page<Department> departmentsPage = departmentService.page(page, pageSize, name);
        return Result.ok(departmentsPage);
    }

    /**
     * 按照id修改部门信息
     * @param department
     * @return
     */
    @PostMapping("/update")
    public Result<Department> update(@RequestBody Department department){
        boolean b = departmentService.updateById(department);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    /**
     * 查询全部
     * @return
     */
    @GetMapping("/findAll")
    public Result<List> findAll(){
        List<Department> list = departmentService.list();
        return Result.ok(list);
    }
    @GetMapping("/get/{id}")
    public Result getById(@PathVariable("id") Long id){
        Department department = departmentService.getById(id);
        return Result.ok(department);

    }

}

